package com.wantup.intecepter;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @ClassName HttpHandShakeIntecepter
 * @Description http 握手拦截器 可以通过这个类的方法 获取request 和response
 * @Author zhaoluowei
 * @Date 2019/6/23  23:37
 * @Version 1.0
 */
//@Component
public class HttpHandShakeIntecepter implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        System.out.println("[握手拦截器] --> beforeHandshake");
        System.out.println(webSocketHandler);
        System.out.println(map);


        if (serverHttpRequest  instanceof ServletServerHttpRequest){
            ServletServerHttpRequest serveletRequest = (ServletServerHttpRequest)serverHttpRequest;
            HttpSession session = serveletRequest.getServletRequest().getSession();
            System.out.println("SessionId  -->  "+session.getId());
            String sessionId = session.getId();
            map.put("sessionId",sessionId);
        }



        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("[握手拦截器] --> afterHandshake");
        if (serverHttpRequest  instanceof ServletServerHttpRequest){
            ServletServerHttpRequest serveletRequest = (ServletServerHttpRequest)serverHttpRequest;
            HttpSession session = serveletRequest.getServletRequest().getSession();
            System.out.println("SessionId  -->  "+session.getId());

        }

    }
}
